package com.ymh.git.thread.juc;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * Created by aivin on 2018/10/30.
 * 统计文件个数
 */
public class SumDirFiles extends RecursiveTask<Integer> {


    private File path;//统计的目录

    public SumDirFiles(File path) {
        this.path = path;
    }


    public static void main(String[] args) {

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        SumDirFiles totalTask = new SumDirFiles(new File("/Users/aivin/Downloads/"));
        forkJoinPool.invoke(totalTask);
        System.out.println("File count= " + totalTask.join());

    }


    @Override
    protected Integer compute() {
        int count = 0;//文件个数计数器
        int dircount = 0;//目录的计数器
        List<SumDirFiles> subTasks = new ArrayList<>(); //子目录任务的容器

        File[] files = path.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    subTasks.add(new SumDirFiles(file));
                    dircount++;
                } else {
                    count++;
                }
            }
        }

        System.out.println("目录：" + path.getAbsolutePath() + "包含的子目录个数" + dircount + "，文件个数：" + count);
        if (!subTasks.isEmpty()) {
            for (SumDirFiles subtask : invokeAll(subTasks)) {
                count = count + subtask.join();
            }
        }
        return count;
    }
}
